package com.mjk.common.core.jdbc.ibatis.typehandler.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import javax.sql.rowset.serial.SerialBlob;
import java.sql.*;

/**
 * blob适配器
 */
public class SerialBlobTypeHandler extends BaseTypeHandler<SerialBlob> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, SerialBlob parameter, JdbcType jdbcType) throws SQLException {
        Blob blob = ps.getConnection().createBlob();
        if (parameter.length() > 0) {
            blob.setBytes(1, parameter.getBytes(1, (int) parameter.length()));
        } else {
            blob.setBytes(1, new byte[0]);
        }
        ps.setBlob(i, blob);
    }

    @Override
    public SerialBlob getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Blob clob = rs.getBlob(columnName);
        if (clob != null) {
            return new SerialBlob(clob);
        }
        return null;
    }

    @Override
    public SerialBlob getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Blob clob = rs.getBlob(columnIndex);
        if (clob != null) {
            return new SerialBlob(clob);
        }
        return null;
    }

    @Override
    public SerialBlob getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Blob clob = cs.getBlob(columnIndex);
        if (clob != null) {
            return new SerialBlob(clob);
        }
        return null;
    }
}
